package org.example.src.service.impl;

import org.example.src.dto.request.LoginRequest;
import org.example.src.dto.request.RegisterRequest;
import org.example.src.dto.response.LoginResponse;
import org.example.src.entity.User;
import org.example.src.repository.UserRepository;
import org.example.src.security.JwtTokenUtil;
import org.example.src.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public LoginResponse login(LoginRequest loginRequest) {
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        loginRequest.getUsername(),
                        loginRequest.getPassword()
                )
        );

        SecurityContextHolder.getContext().setAuthentication(authentication);

        // 修正：从authentication中获取UserDetails对象
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String jwt = jwtTokenUtil.generateToken(userDetails);

        User user = userRepository.findByUsername(loginRequest.getUsername())
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        return new LoginResponse(jwt, user.getId(), user.getUsername(), user.getEmail(), user.getRole());
    }

    @Override
    public User register(RegisterRequest registerRequest) {
        if (userRepository.existsByUsername(registerRequest.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }

        if (userRepository.existsByEmail(registerRequest.getEmail())) {
            throw new RuntimeException("邮箱已被使用");
        }

        User user = new User();
        user.setUsername(registerRequest.getUsername());
        user.setEmail(registerRequest.getEmail());
        user.setPassword(passwordEncoder.encode(registerRequest.getPassword()));
        user.setRole(registerRequest.getRole());

        return userRepository.save(user);
    }

    @Override
    public Boolean validateToken(String token) {
        // 修正：需要提供用户名来验证token，这里简单返回true，实际使用时需要根据具体情况实现
        // 因为接口定义只需要token参数，但JwtTokenUtil需要userDetails，所以需要特殊处理
        try {
            return jwtTokenUtil.validateJwtToken(token); // 使用JwtTokenUtil中的validateJwtToken方法
        } catch (Exception e) {
            return false;
        }
    }
}
